package com.cxb.manager;

import java.io.File;

import java.io.FileWriter;
import java.io.IOException;

import android.content.Context;
import android.os.PowerManager;
import android.os.RecoverySystem;
import android.util.Log;


/**
 * 
 * @{#} RecoveryManager.java Create on 2013-1-22 下午2:18:55    
 *    
 * 类功能说明:   重启进入 Recovery模式
 * @Version 1.0
 * @Author 陈伟斌
 *  
 *
 */
public class RecoveryManager {
	private static final String TAG = "RecoveryManager";
	private static File RECOVERY_DIR = new File("/cache/recovery");
	private static File COMMAND_FILE = new File(RECOVERY_DIR, "command");
	private static File LOG_FILE = new File(RECOVERY_DIR, "log");

	public static void installPackage(Context context, String path, boolean need) throws IOException {
			//MTK平台
			installPackageMTK(context, path, need);
			//三星平台
//			installPackageSANGSUMG(context,new File(path));
	}

	/**
	 * 
	 * 方法描述：三星平台升级接口
	 * @param context
	 * @param packageFile
	 * @throws java.io.IOException
	 */
	public static void installPackageSANGSUMG(Context context, File packageFile) throws IOException {
		RecoverySystem.installPackage(context, packageFile);
	}

	/**
	 * 
	 * 方法描述：MTK平台升级接口
	 * @param context
	 * @param path
	 * @throws java.io.IOException
	 */
	public static void installPackageMTK(Context context, String path, boolean need) throws IOException {
		//String filename = packageFile.getCanonicalPath();
//		if("/mnt/sdcard/".equals(path)){
//			path="/sdcard";
//		}else if("/mnt/sdcard2/".equals(path)){
//			path="/sdcard2";
//		}
		Log.w(TAG, "!!! REBOOTING TO INSTALL " + path + " !!!");
		String arg = "--update_package=" + path;
		if(need)
		{
			arg = "--update_package_wipe_data=" + path;
		}
		Log.w(TAG, "arg = " + arg) ;
		bootCommand(context, arg);
	}

	private static void bootCommand(Context context, String arg) throws IOException {
		RECOVERY_DIR.mkdirs(); // In case we need it
		COMMAND_FILE.delete(); // In case it's not writable
		LOG_FILE.delete();

		FileWriter command = new FileWriter(COMMAND_FILE);
		try {
			command.write(arg);
			command.write("\n");
		} finally {
			command.close();
		}

		// Having written the command file, go ahead and reboot
//		PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//		pm.reboot("recovery");
		RootContext.getInstance().runCommand("reboot recovery");
		throw new IOException("Reboot failed (no permissions?)");
	}
}
